//
//  MXVisibleFooderController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/3.
//

#import "MXVisibleFooderController.h"
#import "MxPublicNav.h"
#import "MXVisibleFooderCommV.h"
#import "MXFooderPlanController.h"
#import "MXHandleAleartV.h"
@interface MXVisibleFooderController ()<MxNavigationViewDelegate>
@property (nonatomic, strong) MxPublicNav *nav;

@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UILabel *tagLab;
@property (nonatomic, strong) UIButton *stateBtn;
@property (nonatomic, strong) UILabel * memberLab;
@property (nonatomic, strong) UILabel *memberTipLab;

@property (nonatomic, strong) UIView *stateV;
@property (nonatomic, strong) UILabel * stateLab;

@property (nonatomic, strong) UILabel *todayCountLab;//出粮分数
@property (nonatomic, strong) UILabel *batteryLevelLab;//电池
@property (nonatomic, strong) UIView *noNetView;
@property (nonatomic, strong) MXVisibleFooderCommV *addV;
@property (nonatomic, strong) MXVisibleFooderCommV *sayV;
@property (nonatomic, strong) MXVisibleFooderCommV *planV;
@property (nonatomic, strong) MXHandleAleartV *addAleart;
@property (nonatomic, strong) MXHandleAleartV *sayAleart;


@property (nonatomic,strong) MXHomeListModel * modelInfo;
@end

@implementation MXVisibleFooderController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor dc_colorWithHexString:@"#ebf4f8"];
    [self createUI];
    [self getDeviceDetail];
}

- (void)getDeviceDetail {

    NSDictionary *param = @{@"deviceName":SAFEPARAMETER(self.model.deviceName),@"productId":self.model.ID};
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/device/describeDevice" params:param httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            weakSelf.modelInfo = [MXHomeListModel mj_objectWithKeyValues:dict[@"data"]];
            
            [weakSelf reloadUI];
        } else {
            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)createUI {
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = SAFEPARAMETER(self.model.deviceLocalName);
    self.nav.delegate = self;
    self.nav.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.nav];
    
    
    self.titleLab = [[UILabel alloc] init];
    self.titleLab.text = @"智能喂食器";
    self.titleLab.font = PFRFontMedium(16);
    self.titleLab.textColor = [UIColor colorWithHexString:@"#000000"];
    [self.view addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.top.offset(kNavBarHeight + 15);
        make.width.mas_lessThanOrEqualTo(kScreenW - 150);
    }];
    
    self.tagLab = [[UILabel alloc] init];
    [self.view addSubview:self.tagLab];
    self.tagLab.textAlignment = NSTextAlignmentCenter;
    self.tagLab.text = @"可视版";
    self.tagLab.textColor = [UIColor dc_colorWithHexString:@"#000000"];
    self.tagLab.font = PFRFont(8);
    self.tagLab.layer.cornerRadius = 4;
    self.tagLab.layer.masksToBounds = YES;
    self.tagLab.layer.borderWidth = 1;
    self.tagLab.layer.borderColor = [UIColor dc_colorWithHexString:@"#000000"].CGColor;
    [self.tagLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLab.mas_right).offset(3);
        make.centerY.mas_equalTo(self.titleLab);
        make.height.mas_equalTo(12);
        make.width.mas_equalTo(39);
    }];
    
    self.stateBtn = [UIButton buttonWithType:0];
    [self.stateBtn setTitle:@"离线" forState:0];
    [self.stateBtn setTitleColor:[UIColor dc_colorWithHexString:@"#000000"] forState:0];
    self.stateBtn.titleLabel.font = PFRFont(14);
//    [self.stateBtn setImage:[UIImage imageNamed:@"home_outline"] forState:0];
    [self.view addSubview:self.stateBtn];
    [self.stateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(46);
        make.height.mas_equalTo(12);
        make.centerY.mas_equalTo(self.titleLab);
        make.right.offset(-13);
    }];
    [self.stateBtn dc_buttonIconLeftWithSpacing:5];
    
    self.memberTipLab = [[UILabel alloc] init];
    [self.view addSubview:self.memberTipLab];
    self.memberTipLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.5];
    self.memberTipLab.font = PFRFont(12);
    self.memberTipLab.text = @"家庭成员";
    [self.memberTipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.top.mas_equalTo(self.titleLab.mas_bottom).offset(5);
//        make.height.mas_equalTo(10);
    }];
    
    self.memberLab = [[UILabel alloc] init];
    [self.view addSubview:self.memberLab];
    self.memberLab.textColor = [UIColor dc_colorWithHexString:@"#000000"];
    self.memberLab.font = PFRFont(12);
    self.memberLab.text = @"";
    [self.memberLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.memberTipLab.mas_right).offset(5);
        make.centerY.mas_equalTo(self.memberTipLab);
    }];
    
    UIView *whiteBg = [[UIView alloc] initWithFrame:CGRectMake(15, kNavBarHeight +24, kScreenW-30, 271)];
    whiteBg.backgroundColor = [UIColor dc_colorWithHexString:@"#FFFFFF" alpha:0.7];
    whiteBg.layer.cornerRadius = 6;
    whiteBg.layer.masksToBounds = YES;
    [self.view addSubview:whiteBg];
    [whiteBg mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.memberTipLab.mas_bottom).offset(10);
        make.left.offset(15);
        make.right.offset(-15);
        make.height.mas_equalTo(271);
    }];
    
    UIView *videoBg = [[UIView alloc] init];
    videoBg.layer.cornerRadius = 6;
    videoBg.layer.masksToBounds = YES;
    videoBg.userInteractionEnabled = YES;
    videoBg.backgroundColor = [UIColor dc_colorWithHexString:@"#D1D1D1" alpha:0.9];
    [whiteBg addSubview:videoBg];
    [videoBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.mas_equalTo(215);
    }];
    
    UIImageView *linkImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fooder_look_link"]];
    [videoBg addSubview:linkImage];
    [linkImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(44);
        make.center.mas_equalTo(videoBg);
    }];
    
    
    self.stateV = [[UIView alloc] init];
    [whiteBg addSubview:self.stateV];
    self.stateV.backgroundColor = [UIColor colorWithHexString:@"#009944"];
    self.stateV.layer.cornerRadius = 3;
    self.stateV.layer.masksToBounds = YES;
    [self.stateV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(6);
        make.left.offset(15);
        make.bottom.equalTo(videoBg).offset(-15);
    }];
    
    self.stateLab = [[UILabel alloc] init];
    self.stateLab.text = @"实时";
    self.stateLab.textColor = [UIColor whiteColor];
    self.stateLab.font = PFRFont(12);
    [whiteBg addSubview:self.stateLab];
    [self.stateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.centerY.mas_equalTo(self.stateV);
    }];
    
    
    self.todayCountLab = [[UILabel alloc] init];
    [whiteBg addSubview:self.todayCountLab];
    self.todayCountLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.7];
    self.todayCountLab.font = PFRFont(12);
    NSString *countStr = @"0";
    NSString *titleStr = [NSString stringWithFormat:@"今日出粮 %@ 份",countStr];
    NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc] initWithString:titleStr];
    [attribut addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:21 weight:UIFontWeightBold]} range:[titleStr rangeOfString:countStr]];
    self.todayCountLab.attributedText = attribut;
    [self.todayCountLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-21);
        make.left.offset(15);
    }];
    
    self.batteryLevelLab = [[UILabel alloc] init];
    [whiteBg addSubview:self.batteryLevelLab];
    self.batteryLevelLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.7];
    self.batteryLevelLab.font = PFRFont(14);
    self.batteryLevelLab.text = @"电量：";
    [self.batteryLevelLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-21);
        make.right.offset(-15);
    }];
    
//    [self.view addSubview:self.noNetView];
//    [self.noNetView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(37);
//        make.left.offset(15);
//        make.right.offset(-15);
//        make.top.mas_equalTo(whiteBg.mas_bottom).offset(16);
//    }];
    
    UIView *bottomV = [[UIView alloc] init];
    bottomV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomV];
    [bottomV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(106);
    }];
    
    [self.view addSubview:self.addAleart];
    [self.addAleart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.bottom.mas_equalTo(bottomV.mas_top).offset(-7);
        make.width.mas_equalTo(151);
        make.height.mas_equalTo(102);
    }];
    
    [self.view addSubview:self.sayAleart];
    [self.sayAleart mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(bottomV.mas_top).offset(-7);
        make.width.mas_equalTo(151);
        make.height.mas_equalTo(102);
    }];

    MJWeakSelf
    self.addV = [[MXVisibleFooderCommV alloc] init];
    [bottomV addSubview:self.addV];
    [self.addV reloadViewWithIconName:@"add_food" bottomTitle:@"立即加餐"];
    [self.addV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tapAdd];
    }]];
    [self.addV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(60);
        make.top.offset(15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(50);
    }];
    
    self.planV = [[MXVisibleFooderCommV alloc] init];
    [bottomV addSubview:self.planV];
    [self.planV reloadViewWithIconName:@"add_plan" bottomTitle:@"喂食计划"];
    [self.planV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tapPlan];
    }]];
    [self.planV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-60);
        make.top.offset(15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(50);
    }];
    
    self.sayV = [[MXVisibleFooderCommV alloc] init];
    [bottomV addSubview:self.sayV];
    [self.sayV reloadViewWithIconName:@"add_say" bottomTitle:@"对讲"];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapSay:)];
    longPress.minimumPressDuration = 1.0;
    longPress.numberOfTouchesRequired = 1;
    [self.sayV addGestureRecognizer:longPress];
    [self.sayV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bottomV);
        make.top.offset(15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(50);
    }];
    
}

-(void)reloadUI{
    self.titleLab.text = [NSString stringWithFormat:@"%@",self.modelInfo.deviceLocalName];
    [self.stateBtn setTitle:(self.modelInfo.deviceStatus == 0 ? @"离线" : @"在线") forState:0];
    [self.stateBtn setTitleColor:[UIColor dc_colorWithHexString:(self.modelInfo.deviceStatus == 0 ? DC_333333 : @"#009944")] forState:0];
    self.memberLab.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.model.deviceForFamilyMemberCount];
    
    NSString *countStr = [NSString stringWithFormat:@"%ld",(long)self.modelInfo.totalFeedCellNum];
    NSString *titleStr = [NSString stringWithFormat:@"今日出粮 %@ 份",countStr];
    NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc] initWithString:titleStr];
    [attribut addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:21 weight:UIFontWeightBold]} range:[titleStr rangeOfString:countStr]];
    self.todayCountLab.attributedText = attribut;
    [self.todayCountLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-21);
        make.left.offset(15);
    }];
    
    self.batteryLevelLab.text = [NSString stringWithFormat:@"电量：%ld%%",(long)self.modelInfo.batteryLevel];
}

- (UIView *)noNetView {
    if (!_noNetView) {
        _noNetView = [[UIView alloc] init];
        _noNetView.userInteractionEnabled = YES;
        _noNetView.backgroundColor = [UIColor whiteColor];
        _noNetView.layer.cornerRadius = 6;
        _noNetView.layer.masksToBounds = YES;
        
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fooder_outline"]];
        [_noNetView addSubview:icon];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(_noNetView);
            make.left.offset(13);
            make.width.mas_equalTo(18);
            make.height.mas_equalTo(16);
        }];
        
        UILabel *noticeLab = [[UILabel alloc] init];
        noticeLab.text = @"设备离线，请检查网络";
        [_noNetView addSubview:noticeLab];
        noticeLab.font = PFRFont(13);
        noticeLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.7];
        [noticeLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(_noNetView);
            make.left.offset(40);
        }];
        
        UIImageView *right = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add_right"]];
        [_noNetView addSubview:right];
        [right mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(8);
            make.height.mas_equalTo(14);
            make.right.offset(-17);
            make.centerY.mas_equalTo(_noNetView);
        }];
    }
    return _noNetView;
}

- (MXHandleAleartV *)addAleart {
    if (!_addAleart) {
        _addAleart = [[MXHandleAleartV alloc] init];
        _addAleart.hidden = YES;
    }
    return _addAleart;
}

- (MXHandleAleartV *)sayAleart {
    if (!_sayAleart) {
        _sayAleart = [[MXHandleAleartV alloc] init];
        _sayAleart.hidden = YES;
        [_sayAleart reloadViewWithTitle:@"对讲中... " subTitle:@"正在对讲，请勿松开"];
    }
    return _sayAleart;
}

-(void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapAdd {
    
    self.addAleart.hidden = NO;
    self.addV.userInteractionEnabled = NO;
    
    MJWeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.addAleart.hidden = YES;
        weakSelf.addV.userInteractionEnabled = YES;
    });
    
    NSString *urlStr = [NSString stringWithFormat:@"%@?deviceId=%@&grainOuput=%@",@"api/app/appFeedingRecord/singleOutput",SAFEPARAMETER(self.model.ID),@"1"];
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
         NSDictionary * dict = [responseObject mj_JSONObject];
         [weakSelf.view hideToastActivity];
         if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
             [weakSelf.view xjmakeToast:@"加餐成功"];
             
             weakSelf.modelInfo.totalFeedCellNum++;
             [weakSelf reloadUI];
         } else {

             [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
         }
     } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
         [weakSelf.view hideToastActivity];
         
         [weakSelf.view xjmakeToast:@"加餐失败"];
         weakSelf.addAleart.hidden = YES;
         weakSelf.addV.userInteractionEnabled = YES;
     }];
    
}

- (void)tapSay:(UILongPressGestureRecognizer *)sender {
    self.addAleart.hidden = YES;
    if (sender.state == UIGestureRecognizerStateBegan) {
        self.sayAleart.hidden = NO;
    }
    
    if (sender.state == UIGestureRecognizerStateEnded) {
        self.sayAleart.hidden = YES;
    }
}

- (void)tapPlan {
    MXFooderPlanController *planVc = [[MXFooderPlanController alloc] init];
    planVc.model = self.model;
    [self.navigationController pushViewController:planVc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

@end
